<?php
/**
 * Created by PhpStorm.
 * User: Sixstar-Peter
 * Date: 2019/4/13
 * Time: 21:43
 */
//1.在某个特定的状态主动让出cpu的执行权限(中断执行)
//2.一旦程序状态改变,能够恢复程序的执行


//foreach (range(0, 10000000) as $number) {
//      //echo $number;
//
//}

//function xrange($start,$end){
//    //for ($i=$start;$i<$end;$i++){
//         yield "test";  //中断
//    //}
//}
//
//var_dump(xrange(1,100)->current());
//$ger=xrange(1,100);
//var_dump($ger->current());
//while (true){
//    $res=$ger->send(1); //恢复执行,继续往下执行
//    var_dump($res);
//    sleep(1);
//}


//var_dump($ger->next());
//var_dump(xrange(1,100));
//foreach (xrange(1,100) as $num ){
//
//    var_dump($num);
//}


function coro1()
{
    //查mysql
//    for ($i=0;$i<5;$i++){
//        echo "协程1:".$i.PHP_EOL;
//        sleep(1); //睡眠了,发生了IO阻塞了
//        yield;  //中断
//    }
    $ch1 = curl_init();
    curl_setopt($ch1, CURLOPT_URL, "http://47.98.147.49/index.php");
    curl_setopt($ch1, CURLOPT_HEADER, 0);
    $mh = curl_multi_init();
    curl_multi_add_handle($mh, $ch1);
    do {
        $mrc = curl_multi_exec($mh, $running);
        //请求发出后，让出cpu
        yield false;
        //var_dump($running);

    } while ($running > 0);
    $ret = curl_multi_getcontent($ch1);
    echo $ret . "1" . PHP_EOL;
    yield true;
}

function coro2()
{
    //调api
//    for ($i=0;$i<5;$i++){
//        //yield "test";  //中断
//        echo "协程2:".$i.PHP_EOL;
//        sleep(1); //睡眠了,发生了IO阻塞了
//        yield;  //中断,并且保存了状态
//    }

    $ch1 = curl_init();
    curl_setopt($ch1, CURLOPT_URL, "http://47.98.147.49/index.php");
    curl_setopt($ch1, CURLOPT_HEADER, 0);
    $mh = curl_multi_init();
    curl_multi_add_handle($mh, $ch1);
    do {
        $mrc = curl_multi_exec($mh, $running);
        //请求发出后，让出cpu
        yield false;
    } while ($running > 0);
    $ret = curl_multi_getcontent($ch1);
    echo $ret . "2" . PHP_EOL;
    yield true;
}

$co = coro1();
$co1 = coro2();

//调度器
while (true) {
    $res1 = $co->current();
    $res2 = $co1->current();
    //恢复执行,继续往下执行
    $co->next();
    $co1->next();

    if ($res1) { //优化下可以通过获取结果之后就跳出循环
        break;
    }
    usleep(1000);
}





